<template>
  <div class='container'>
    <div class="header">
      <span class="tip_text">说明:目前支持学科和关键字条件筛选</span>
      <el-button style="float: right;" type="success" size="small" icon="el-icon-edit" @click="hCreated">新增试题</el-button>
    </div>
    <div class="center">
      <el-form ref="form" :model="form" label-width="80px" size='small'>
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科" prop='subjectID'>
              <el-select v-model="form.subjectID" placeholder="请选择" @change="doChange">
                <el-option v-for="(list, index) in subNameList" :key="index" :label="list.label" :value="list.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录" prop='catalogID'>
              <el-select v-model="form.catalogID" placeholder="请选择">
                <el-option v-for="(list, index) in twoCataList" :key="index" :label="list.label" :value="list.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签" prop='tags'>
              <el-select v-model="form.tags" placeholder="请选择">
                <el-option v-for="(list, index) in tagsList" :key="index" :label="list.label" :value="list.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字" prop='keyword'>
              <el-input v-model="form.keyword" placeholder="根据题干搜索"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="试题类型" prop='questionType'>
              <el-select v-model="form.questionType" placeholder="请选择">
                <el-option v-for="type in questionType" :key="type.value" :label="type.label" :value="type.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度" prop='difficulty'>
              <el-select v-model="form.difficulty" placeholder="请选择">
                <el-option v-for="(list, index) in difficulty" :key="index" :label="list.label" :value="list.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向" prop='direction'>
              <el-select v-model="form.direction" placeholder="请选择">
                <el-option v-for="(list, index) in direction" :key="index" :label="list" :value="list"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人" prop='creatorID'>
              <el-select v-model="form.creatorID" placeholder="请选择">
                <el-option v-for="(list, index) in creatorList" :key="index" :label="list.username" :value="list.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="题目备注" prop='remarks'>
              <el-input v-model="form.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称" prop='shortName'>
              <el-input v-model="form.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-row>
              <el-form-item label="城市">
                  <el-col :span="12" gutter="1">
                    <el-form-item prop='province'>
                      <el-select v-model="form.province" placeholder="请选择"
                      @change="hProvince">
                        <el-option v-for="(list, index) in citySelect.province" :key="index" :label="list" :value="list"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" class="city">
                    <el-form-item prop="city">
                      <el-select v-model="form.city"
                      placeholder="请选择">
                        <el-option v-for="(list, index) in citySelect.citys" :key="index" :label="list" :value="list"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="6">
            <el-form-item class="btn-right">
              <el-button @click="resetForm" size="small">清除</el-button>
              <el-button type="primary" @click="hSearch" size="small" >搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-tabs v-model="chkState" type="card" @tab-click="handleClick">
      <el-tab-pane label="全部" name="null"></el-tab-pane>
      <el-tab-pane label="待审核" name="0"></el-tab-pane>
      <el-tab-pane label="已审核" name="1"></el-tab-pane>
      <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
    </el-tabs>
    <el-alert
      :title='alertText'
      type="info"
      show-icon
      :closable="false">
    </el-alert>
    <el-table
      :data="tableData"
      v-loading="isloading"
      style="width: 100%">
      <el-table-column
        prop="number"
        label="试题编号"
        width="120">
      </el-table-column>
      <el-table-column
        prop="subject"
        label="学科"
        width="120">
      </el-table-column>
      <el-table-column
        prop="catalog"
        label="目录"
        width="120">
      </el-table-column>
      <el-table-column
        label="题型"
        width="120">
        <template slot-scope='scope'>
          <div v-for="type in questionType" :key="type.value">
            <span v-if="Number(scope.row.questionType) === type.value">{{ type.label }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="题干"
        width="300">
        <template  slot-scope="scope">
          <div style="margin-left: 10px" v-html="scope.row.question"></div>
        </template>
      </el-table-column>
      <el-table-column
        prop="addDate"
        label="录入时间"
        width="160">
         <template #default="{ row }">
              {{ formatEntry(row.addDate) }}
            </template>
      </el-table-column>
      <el-table-column
        label="难度"
        width="90">
        <template slot-scope="scope">
          <div v-for="item in difficulty" :key="item.value">
            <span v-if="Number(scope.row.difficulty) === item.value">{{ item.label }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="creator"
        label="录入人"
        width="120">
      </el-table-column>
      <el-table-column
        label="审核状态"
        width="120">
        <template slot-scope="scope">
          {{ scope.row.chkState === 1 ? '已审核' : (scope.row.chkState === 2 ? '已拒绝' : '待审核') }}
        </template>
      </el-table-column>
      <el-table-column
        prop="chkRemarks"
        label="审核意见"
        width="120">
      </el-table-column>
      <el-table-column
        prop="chkUser"
        label="审核人"
        width="120">
      </el-table-column>
      <!-- 在constants.js里面 -->
      <el-table-column
        label="发布状态"
        width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.chkState === 0 || scope.row.chkState === 2">待发布</span>
          <span v-else-if="scope.row.publishState === 1">已发布</span>
          <span v-else-if="scope.row.publishState === 0">已下架</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button @click="hAlert(scope.row)" type="text" size="small">预览</el-button>
          <el-button type="text" size="small" @click="hAudit(scope.row)" :disabled='Number(scope.row.chkState) !== 0'>审核</el-button>
          <el-button type="text" size="small" @click="hEdit(scope.row.id)" :disabled="scope.row.publishState !== 0">修改</el-button>
          <el-button type="text" size="small" @click="hPublishState(scope.row)">{{ scope.row.publishState === 1 ? '下架' : '上架' }}</el-button>
          <el-button type="text" size="small" @click="hDelData(scope.row)" :disabled='scope.row.publishState === 1'>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      @size-change='hSizeChange'
      @current-change="hCurrentChange"
      :current-page="form.page"
      :page-sizes="[2, 3, 5 , 10 ]"
      :page-size='2'
      layout=" prev, pager, next, sizes, jumper"
      :disabled='isloading'
      :total="total">
    </el-pagination>

    <!-- 题目审核弹出框 -->
    <el-dialog
      title="题目审核"
      :visible.sync="dialogVisible"
      width="30%"
      v-if="dialogVisible">
      <questions-check :subID='subID' @close='dialogVisible=false' @refresh='loadData'></questions-check>
    </el-dialog>

    <!-- 预览弹出框 -->
    <el-dialog
      title="题目预览"
      :visible.sync="dialogPreview"
      width="60%"
      v-if="dialogPreview">
      <questions-preview :subID='subID' @close='dialogPreview=false'></questions-preview>
    </el-dialog>
  </div>
</template>

<script>
import { choice, choicePublish, remove } from '@/api/hmmm/questions'
import { simple as twoSimple } from '@/api/hmmm/directorys' // 二级目录
import { simple as creatorSimple } from '@/api/base/users' // 录入人
import { simple as tagSimple } from '@/api/hmmm/tags' // 标签目录
import { simple } from '@/api/hmmm/subjects'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
// 日期格式化
import dayjs from 'dayjs'
// 试题审核
import QuestionsCheck from '../components/questions-check.vue'
// 题目预览
import QuestionsPreview from '../components/questions-preview.vue'
export default {
  name: 'question-choice',
  components: {
    QuestionsCheck,
    QuestionsPreview
  },
  data () {
    return {
      form: {
        page: 1, // 当前页数
        pagesize: 2,
        subjectID: null, // 学科
        difficulty: null, // 难度
        questionType: null, // 试题类型
        tags: null, // 标签名称
        city: null, // 企业所在城市
        province: null, // 城市下地区
        keyword: null, // 关键字
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        direction: null, // 方向
        creatorID: null, // 录入人
        catalogID: null // 目录
      },
      chkState: 'null', // 审核状态  0 待审核 1 通过 2 拒绝
      publishState: 0, // 1 上架 0 下架 其他待发布
      total: 0,
      alertText: '',
      tableData: [],
      isloading: false, // 加载效果
      subNameList: [], // 学科列表
      twoCataList: [], // 二级目录列表
      tagsList: [], // 标签列表
      creatorList: [], // 录入人列表
      citySelect: {
        province: '',
        citys: ''
      },
      dialogVisible: false, // 对话框
      dialogPreview: false, // 搜索对话框
      subID: '' // 预览存放的当前行的数据
    }
  },
  created () {
    this.loadSubName() // 学科下拉选择框
    this.loadData() // 表格的数据
    this.getCreator() // 渲染录入人
    this.getCityData() // 渲染城市的下拉列表框
  },
  computed: {
    questionType () {
      return questionType
    },
    difficulty () {
      return difficulty
    },
    direction () {
      return direction
    }
  },
  methods: {
    formatEntry (yan) {
      return dayjs(yan).format('YYYY-MM-DD HH:mm:ss')
    },
    async loadSubName () {
      try {
        const { data: res } = await simple()
        this.subNameList = res
      } catch (err) {
        console.log(err)
      }
    },
    // 获取请求参数
    getParams () {
      const params = Object.assign({}, this.form)
      params.chkState = this.chkState !== 'null' ? this.chkState : null
      return params
    },
    // 初识化,和搜索按钮的事件
    async loadData () {
      const params = this.getParams()
      try {
        this.isloading = true
        const { data: res } = await choice(params)
        this.tableData = res.items
        this.total = res.counts
        this.alertText = `共${res.counts}条数据`
        this.isloading = false
      } catch (err) {
        console.log(err)
        this.isloading = false
      }
    },
    resetForm () { // 重置清空表单
      this.$refs.form.resetFields()
      this.twoCataList = []
      this.tagsList = []
    },
    hSearch () { // 搜索按钮
      this.form.page = 1
      this.loadData()
    },
    // tab栏切换
    handleClick () {
      this.form.page = 1
      this.loadData()
    },
    // 点击分页触发
    hCurrentChange (curPage) {
      this.form.page = curPage
      this.loadData()
    },
    // pageSize条数 改变时会触发
    hSizeChange (size) {
      this.form.pagesize = size
      this.form.page = 1
      this.loadData()
    },
    // 学科下拉选择框改变二级目录
    doChange () {
      this.form.catalogID = null
      this.form.tags = null
      this.getDatalogID() // 二级目录
      this.getTags() // 标签
    },
    // 获取二级目录
    async getDatalogID () {
      try {
        const res = await twoSimple({ subjectID: this.form.subjectID })
        console.log(res)
        this.twoCataList = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取标签目录
    async getTags () {
      try {
        const res = await tagSimple({ subjectID: this.form.subjectID })
        this.tagsList = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取录入人
    async getCreator () {
      try {
        const res = await creatorSimple()
        this.creatorList = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取城市
    getCityData () {
      this.citySelect.province = provinces()
    },
    // 城市的二级联动 值改变查询province的数据
    hProvince () {
      this.citySelect.citys = citys(this.form.province)
      this.form.city = this.citySelect.citys[0]
    },
    // 点击上架下架切换状态
    hPublishState (row) {
      const { id, publishState: state } = row
      const msg = state === 1 ? '下架' : '上架'
      const text = `您确定 ${msg} 这道题目嘛?`
      const publishState = state === 1 ? 0 : 1
      this.$confirm(text, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doPublish(id, publishState, msg, row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    async doPublish (id, publishState, msg, row) {
      try {
        await choicePublish({ id, publishState })
        this.$message({
          type: 'success',
          message: `${msg}成功`
        })
        row.publishState = row.publishState === 1 ? 0 : 1
      } catch (err) {
        this.$message({
          type: 'error',
          message: `${msg}失败`
        })
      }
    },
    // 点击删除
    hDelData (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id
        this.doDelte(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async doDelte (id) {
      try {
        const res = await remove({ id })
        if (this.tableData.length === 1 && this.form.page > 1) this.form.page--
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        console.log(res)
        this.loadData() // 重新加载页面
      } catch (err) {
        this.$message({
          type: 'error',
          message: '删除失败!'
        })
        console.log(err)
      }
    },
    // 预览弹框
    hAlert (row) {
      this.dialogPreview = true
      this.subID = row.id
    },
    // 点击审核
    hAudit (row) {
      this.subID = row.id
      this.dialogVisible = true
    },
    // 点击新增试题跳转
    hCreated () {
      this.$router.push('/questions/new')
    },
    // 点击修改按钮跳转页面
    hEdit (id) {
      this.$router.push('/questions/new?id=' + id)
    }
  }
}
</script>

<style scoped lang='css'>
.container {
  background-color: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 5px;
}

.header {
  overflow: hidden;
}

.header .tip_text {
  color: pink;
  font-size: 12px;
}

.center {
  margin-top: 10px;
}

.btn-right {
  text-align: right;
}

.el-pagination {
  margin-top: 10px;
  text-align: right;
}

.el-select {
  display: block;
}

.city {
  padding-left: 10px;
}

.el-alert {
  margin-bottom: 10px;
}
.el-pagination /deep/ .el-pagination__jump {
  margin-left: 0;
}

.el-table /deep/ .hljs-built_in, .hljs-type {
  color: #4ec9b0
}
.el-table /deep/ .cell {
  text-align: center;
}
</style>
